package com.yzt.index;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleRegistry;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;

import com.yzt.p_base.utils.ToastUtil;
import com.yzt.zhuju.IService.account.IAccountService;
import com.yzt.zhuju.IService.call.ICallService;
import com.yzt.zhuju.IService.chatroom.IChatRoomService;
import com.yzt.zhuju.IService.message.IMessageService;
import com.yzt.zhuju.IService.message.UnReadMessageCountChangeObserver;
import com.yzt.zhuju.MainMenuContsant;
import com.yzt.zhuju.RXingUtils;
import com.yzt.zhuju.arouter.RouterAccount;
import com.yzt.zhuju.arouter.RouterMain;
import com.yzt.zhuju.arouter.RouterUser;
import com.yzt.zhuju.base.BaseActivity;
import com.yzt.zhuju.config.AppConfigCacheManager;

import com.yzt.zhuju.dialog.BottomBaseDialog;
import com.yzt.zhuju.event.RxBus;
import com.yzt.zhuju.event.call.ChatRoomButtonClick;
import com.yzt.zhuju.event.im.RongYunLoginEvent;
import com.yzt.zhuju.event.im.RongYunLoginSuccessEvent;
import com.yzt.zhuju.event.im.RongYunMessageUnreadStatusEvent;
import com.yzt.zhuju.event.im.TurnToUnReadEvent;
import com.yzt.zhuju.event.main.ExitAppEvent;
import com.yzt.zhuju.event.main.IndexVideoEvent;
import com.yzt.zhuju.event.main.LoginCloseEvent;
import com.yzt.zhuju.event.main.MainSwitchEvent;
import com.yzt.zhuju.event.main.MainSwitchPageEvent;
import com.yzt.zhuju.event.main.MainTabEvent;
import com.yzt.zhuju.event.main.MainTaskEvent;
import com.yzt.zhuju.event.user.GameAddEvent;
import com.yzt.zhuju.file.FileDownloadManager;
import com.yzt.zhuju.gift.GiftManager;
import com.yzt.zhuju.network.AresSubscriber;
import com.yzt.zhuju.network.biz.BizLayer;
import com.yzt.zhuju.network.entity.call.AgoraCallMsg;
import com.yzt.zhuju.network.entity.user.PersonalDetailBasic;
import com.yzt.zhuju.network.entity.user.UserLoginInfo;
import com.yzt.zhuju.permission.PermissionsUtils;
import com.yzt.zhuju.utils.ActivityManagerUtils;
import com.yzt.zhuju.utils.DeviceUtils;
import com.yzt.zhuju.utils.PersonalDetailCacheManager;
import com.yzt.zhuju.utils.Utils;
import com.yzt.zhuju.voice.VoicePlayManager;
import com.yzt.zhuju.widget.tuiview.TUIImageView;
import com.yzt.index.bean.MainInfo;
import com.yzt.zhuju.constants.PreferenceConstant;
import com.yzt.index.dialog.MainIndexDialog;
import com.yzt.p_base.utils.LogDataUtils;
import com.yzt.p_base.utils.SharedPreferenceUtil;
import com.yzt.p_base.utils.StringUtils;
import com.yzt.plugin_widget.tableBar.CommonTabLayout;
import com.yzt.plugin_widget.tableBar.listener.OnTabSelectListener;
import com.yzt.plugin_widget.viewPager.NoScrollViewPager;
import com.yzt.plugin_widget.viewPager.ViewPagerAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;

import cn.jpush.android.api.JPushInterface;
import cn.jzvd.Jzvd;

/**
 * @author Administrator
 * <p>
 * 首页
 */
@SuppressLint({"DefaultLocale", "MissingSuperCall"})
@Route(path = RouterMain.ACTIVITY_MAIN)
public class MainActivity extends BaseActivity implements OnTabSelectListener {

    @Autowired
    IMessageService messageService;

    @Autowired
    IAccountService accountService;

    @Autowired
    IChatRoomService chatRoomService;

    @Autowired
    ICallService callService;

    @Autowired
    boolean jumpCallChat;

    @Autowired
    AgoraCallMsg msg;

    @Autowired
    String roomId;

    @Autowired
    String mUserId;

    /**
     * 版本更新
     */
    private static final String TASK_UPDATE = "task_update";

    /**
     * 完善个人资料
     */
    private static final String TASK_IMPROVE_PERSONAL_DATA = "task_improve_personal_data";

    private NoScrollViewPager mMainPager;
    private CommonTabLayout commontablayout;
    private final Queue<String> mTaskList = new LinkedList<>();

    private boolean isRegisterComeIn;

    private boolean isResetTask;

    private TUIImageView tab1, tab2, tab3, tab4, tab5;

    private int currentType = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setFullScreen(true);
        hindBottomBar();
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        if (getLifecycle() instanceof LifecycleRegistry) {
            ((LifecycleRegistry) getLifecycle()).markState(Lifecycle.State.CREATED);
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_core_main;
    }

    @Override
    public void installViews() {
        isDark = false;

        mMainPager = findViewById(R.id.main_view_pager);
        mMainPager.setNoScroll(true);
        commontablayout = findViewById(R.id.main_tab_layout);
        tab1 = findViewById(R.id.img_tab1);
        tab1.setOnClickListener(this);
        tab1.setSelected(true);
        tab2 = findViewById(R.id.img_tab2);
        tab2.setOnClickListener(this);
        tab3 = findViewById(R.id.img_tab3);
        tab3.setOnClickListener(this);
        tab4 = findViewById(R.id.img_tab4);
        tab4.setOnClickListener(this);
        tab5 = findViewById(R.id.img_tab5);
        tab5.setOnClickListener(this);
        initFragment();
        RxBus.getDefault().post(new LoginCloseEvent());
        mStatusBarLayout.setVisibility(View.VISIBLE);
        if (msg == null) {
            if (getIntent().hasExtra("AgoraCallMsg")) {
                msg = (AgoraCallMsg) getIntent().getSerializableExtra("AgoraCallMsg");
            }
        }
        AppConfigCacheManager.getInstance().isLoginOut = false;
        FileDownloadManager.getInstance().init(mActivity);
        parseIntent(getIntent());
        initDeviceId();
        registerRxBus();

        isRegisterComeIn = false;
        regAfterExecFun();

        //设置未读消息的类型
        setUnReadCount();

        //登录融云
        ARouter.getInstance().navigation(IMessageService.class).login();

        // 获取用户信息
        getUserInfo();

        // 获取系统配置
        AppConfigCacheManager.getInstance().getSysConfig();

        // 绑定推送
        bindPush();

        // 获取礼物
        GiftManager.getInstance().getGiftListData();
    }

    private void bindPush() {
        Map<String, String> map = new HashMap<>();
        map.put("deviceId", JPushInterface.getRegistrationID(Utils.getApp()));
        map.put("platformType", "2");
        BizLayer.getInstance().getAccountModule().bindPush(map, new AresSubscriber<Object>() {
            @Override
            protected void onSuccess(Object personalDetail) {

            }
        });
    }

    /**
     * 获取用户信息填充
     */
    private void getUserInfo() {
        if (RXingUtils.getUserId() != null) {
            // 用户信息
            Map<String, String> map = new HashMap<>();
            map.put("userId", RXingUtils.getUserId());
            BizLayer.getInstance().getAccountModule().getFullInfoParts(map, new AresSubscriber<PersonalDetailBasic>() {
                @Override
                protected void onSuccess(PersonalDetailBasic personalDetail) {
                    PersonalDetailCacheManager.addPersonalDetail(personalDetail);
                    RXingUtils.savePersonDetail(personalDetail);
                }
            });
        }
    }

    /**
     * 账号切换后刷新数据
     */
    @Override
    public void refreshScreen() {
        super.refreshScreen();
        initFragment();
        //登录融云
        RxBus.getDefault().post(new RongYunLoginEvent());
        currentType = 0;
        onTabSelect(0);
        isResetTask = true;
    }

    private boolean isRegFunExec = false;

    /**
     * 注册后执行得方法，设置男女处于注册中
     */
    private void regAfterExecFun() {
        if (isRegFunExec) {
            return;
        }
        if (isRegisterComeIn) {
            return;
        }

        isRegFunExec = true;
        homeTask();
        //消息顶部弹窗
        messageService.registerFloatMessage();
    }

    public void homeTask() {

        mTaskList.offer(TASK_UPDATE);

        if (MainMenuContsant.isHaveChatRoom()) {
            //女用户
            mTaskList.offer(TASK_IMPROVE_PERSONAL_DATA);
        }
        RxBus.getDefault().post(new MainTaskEvent());
    }

    private void initFragment() {
        MainInfo mainMenuInfo = MainMenuHelper.getMainMenuInfo();
        commontablayout.setTabData(mainMenuInfo.getCustomTabList());
        ViewPagerAdapter mAdapter = new ViewPagerAdapter(getSupportFragmentManager(),
                mainMenuInfo.getFragmentList(),
                mainMenuInfo.getTitleArray());
        mMainPager.setAdapter(mAdapter);
        mMainPager.setOffscreenPageLimit(mainMenuInfo.getCustomTabList().size());
        commontablayout.setOnTabSelectListener(this);
    }

    /**
     * 设置消息未读消息的类型
     */
    private void setUnReadCount() {
        messageService.addUnReadCountChangeObserver(imUnReadMessageObserver);
    }

    private final IMUnReadMessageObserver imUnReadMessageObserver = new IMUnReadMessageObserver();

    private static class IMUnReadMessageObserver implements UnReadMessageCountChangeObserver {

        @Override
        public void onChange(int count) {
            RxBus.getDefault().post(new RongYunMessageUnreadStatusEvent(count));
        }

        @Override
        public void onError(int code, String msg) {

        }
    }

    /**
     * 注册广播
     */
    public void registerRxBus() {
        //主页任务执行
        observerRxBus(MainTaskEvent.class, mainTaskEvent -> {
            String taskName = mTaskList.poll();
            if (StringUtils.isEmpty(taskName)) {
                return;
            }
            if (!RXingUtils.isLogin()) {
                return;
            }
            LogDataUtils.d("MainTask", taskName);
            mHandler.postDelayed(() -> {
                if (taskName.equals(TASK_IMPROVE_PERSONAL_DATA)) {
                    showNewPerfectDialog();
                } else {
                    RxBus.getDefault().post(new MainTaskEvent());
                }
            }, 1000);
        });

        //融云未读状态更新
        observerRxBus(RongYunMessageUnreadStatusEvent.class, event -> {
            if (MainMenuContsant.isHaveChatRoom()) {
                commontablayout.showMsg(MainMenuContsant.getIndex(MainMenuContsant.MAIN_MENU_MSG), event.getNum());
            }
        });

        //主页页面切换
        observerRxBus(MainSwitchPageEvent.class, event ->
                onTabSelect(MainMenuContsant.getIndex(event.getType()))
        );

        // 退出登录
        observerRxBus(ExitAppEvent.class, event -> {
            if (AppConfigCacheManager.getInstance().isLoginOut) {
                return;
            }
            if (event.getType() == 0) {
                Log.i("MainActivity", "exit app");
                Log.i("gz-base", "logout start");
                if (AppConfigCacheManager.getInstance().isLoginOut) {
                    return;
                }
                AppConfigCacheManager.getInstance().isLoginOut = true;
                messageService.logout();
                ActivityManagerUtils.getInstance().finishAllActivity();
                RXingUtils.logout();
                RouterAccount.LoginActivity(1, event.getContent());
                Log.i("gz-base", "logout end");
                finish();
            }
        });

        // 融云登录回调
        observerRxBus(RongYunLoginSuccessEvent.class, event ->
                setUnReadCount()
        );

        //跳转首页下面指定的tab
        observerRxBus(MainTabEvent.class, mainTabEvent -> {
            String event = mainTabEvent.getEvent();
            if (event.equals(MainMenuContsant.MAIN_MENU_NEARBY)) {
                int position = MainMenuContsant.getIndex(event);
                onTabSelect(position);
            } else if (event.equals(MainMenuContsant.MAIN_MENU_CHATROOM)) {
                int position = MainMenuContsant.getIndex(event);
                onTabSelect(position);
            } else if (event.equals(MainMenuContsant.MAIN_MENU_MSG)) {
                int position = MainMenuContsant.getIndex(event);
                onTabSelect(position);
            } else if (event.equals(MainMenuContsant.MAIN_MENU_MINE)) {
                int position = MainMenuContsant.getIndex(event);
                onTabSelect(position);
            } else if ("CHATROOM_BUTTON_MORE".equals(event)) {
                //打开
                RxBus.getDefault().post(new ChatRoomButtonClick("more"));
            }
        });

        // 发布游戏成功
        observerRxBus(GameAddEvent.class, event -> {
            currentType = 0;
            onTabSelect(0);
        });
    }

    /**
     * 完善个人资料
     */
    private void showNewPerfectDialog() {

        if (!RXingUtils.isShowNewPerfectDialog) {
            RxBus.getDefault().post(new MainTaskEvent());
            return;
        }

        UserLoginInfo mUserLoginInfo = RXingUtils.getLoginAccount();

        if (mUserLoginInfo == null || mUserLoginInfo.getUserInfo() == null) {
            RxBus.getDefault().post(new MainTaskEvent());
            return;
        }

        RXingUtils.isShowNewPerfectDialog = false;
    }

    @Override
    public void onTabSelect(int position) {
        MainMenuContsant.mMainPageIndex = position;
        commontablayout.setCurrentTab(position);
        mMainPager.setCurrentItem(position);
        if (position != 0) {
            VoicePlayManager.getInstance().stopPlay();
            Jzvd.goOnPlayOnPause();
        }
        tab1.setSelected(position == 0);
        tab2.setSelected(position == 1);
        tab4.setSelected(position == 2);
        tab5.setSelected(position == 3);
        RxBus.getDefault().post(new MainSwitchEvent(position));
    }

    @Override
    public void onTabReselect(int position) {
        if (position == MainMenuContsant.getIndex(MainMenuContsant.MAIN_MENU_MSG)) {
            RxBus.getDefault().post(new TurnToUnReadEvent());
        }
    }

    private void initDeviceId() {
        if (SharedPreferenceUtil.getInstance().getValue(PreferenceConstant.SHOW_PHONE_STATUS_DIALOG, true)) {
            SharedPreferenceUtil.getInstance().putValue(PreferenceConstant.SHOW_PHONE_STATUS_DIALOG, false);
            try {
                String IMeiCode = DeviceUtils.getAndroidID(this);
                if (!StringUtils.isEmpty(IMeiCode) && !IMeiCode.matches("^0+$")) {
                    RXingUtils.saveDeviceId(IMeiCode);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.e("收到Agora来电", "app恢复");
        regAfterExecFun();
        setIntent(intent);
        parseIntent(intent);
    }

    private void parseIntent(Intent intent) {
        if (intent.hasExtra("roomId")) {
            chatRoomService.enterChatRoom(getIntent().getStringExtra("roomId"));
            return;
        }

        if (intent.hasExtra("mUserId")) {
            RouterUser.PersonalDetailActivity(getIntent().getStringExtra("mUserId"));
            return;
        }

        if (intent.getAction() != null) {
            if (!intent.getAction().equals(Intent.ACTION_MAIN)) {
                //h5打开
                if (intent.getData() != null) {
                    //有activity已打开，直接跳到指定页面
                    if (ActivityManagerUtils.getInstance().haveActivity()) {
                        Uri data = intent.getData();
                        String main = intent.getData().getQueryParameter("main");
                        String page = data.getQueryParameter("page");       //房间设置
                        String webUrl = data.getQueryParameter("webUrl");   //打开h5页面
                        String webParam = data.getQueryParameter("webParam");
                        String event = data.getQueryParameter("event");
                        if (!TextUtils.isEmpty(main)) {
                            return;
                        }
                        if (TextUtils.isEmpty(event)) {
                            open(webUrl, page, webParam);
                            return;
                        }
                        switch (event) {
                            case "chatRoom":
                                HashMap<String, String> params = new HashMap<>();
                                params.put("inviteEnterUid", data.getQueryParameter("inviteEnterUid"));
                                chatRoomService.enterChatRoom(data.getQueryParameter("id"), params);
                                break;
                            case "personalDetal":
                                RouterUser.PersonalDetailActivity(data.getQueryParameter("id"));
                                break;
                            default:
                                open(webUrl, page, webParam);
                                break;
                        }
                    }
                }
            }
        }
    }

    public void open(String webUrl, String page, String webParam) {
        if (!TextUtils.isEmpty(webUrl)) {//跳转h5页面
            if (!TextUtils.isEmpty(webParam)) {
                webUrl = webUrl + "#/" + webParam;
            }
            RouterMain.goToWeb(webUrl);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isResetTask) {
            isResetTask = false;
            if (mTaskList != null) {
                mTaskList.clear();
                homeTask();
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        Jzvd.goOnPlayOnPause();
        VoicePlayManager.getInstance().stopPlay();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        messageService.removeUnReadCountChangeObserver(imUnReadMessageObserver);
        messageService.unregisterFloatMessage();
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    protected void onClick(int clickId) {
        super.onClick(clickId);

        if (clickId == R.id.img_tab1) {
            if (currentType != 0) {
                RxBus.getDefault().post(new IndexVideoEvent(1));
            }
            currentType = 0;
            onTabSelect(0);
        }
        if (clickId == R.id.img_tab2) {
            currentType = 1;
            onTabSelect(1);
            RxBus.getDefault().post(new IndexVideoEvent(2));
        }
        if (clickId == R.id.img_tab3) {

            // 权限校验

            List<String> permissions = new ArrayList<>();

            if (android.os.Build.VERSION.SDK_INT >= 33) {
                permissions.add(Manifest.permission.CAMERA);
                permissions.add(Manifest.permission.READ_MEDIA_AUDIO);
                permissions.add(Manifest.permission.READ_MEDIA_IMAGES);
                permissions.add(Manifest.permission.READ_MEDIA_VIDEO);
            } else {
                permissions.add(Manifest.permission.CAMERA);
                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            }

            PermissionsUtils.getInstance().checkPermission(mActivity, permissions, "camera", new PermissionsUtils.OnCallBackListener() {
                @Override
                public void open(List<String> list) {
                    BottomBaseDialog.showDialog(MainActivity.this, MainIndexDialog.class);
                }

                @Override
                public void notOpen(List<String> list, String label) {
                    ToastUtil.showMessage(getString(R.string.go_set_open_permission));
                }
            });

        }
        if (clickId == R.id.img_tab4) {
            currentType = 2;
            onTabSelect(2);
            RxBus.getDefault().post(new IndexVideoEvent(2));
        }
        if (clickId == R.id.img_tab5) {
            currentType = 3;
            onTabSelect(3);
            RxBus.getDefault().post(new IndexVideoEvent(2));
        }
    }
}